/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author kempe
 */
@WebService()
public class NewWebService {
    String baseURL;
    DocumentBuilder docBuild;
    TransformerFactory transFac;

    public NewWebService() throws MalformedURLException, ParserConfigurationException {
        baseURL = "http://localhost:8080/DatabaseService/article/article/";
        DocumentBuilderFactory docBuildFac = DocumentBuilderFactory.newInstance();
        docBuild = docBuildFac.newDocumentBuilder();
        transFac = TransformerFactory.newInstance();
    }
    
    
    
    
    @WebMethod(operationName = "listArticles")
    public String listArticles(@WebParam(name = "count")
    String count) {
        try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(count));
        Document doc = docBuild.parse(is);
        
        Integer c = null;
        c = Integer.parseInt(((CharacterData) doc.getElementsByTagName("count").item(0).getFirstChild()).getData());
        URL u = new URL(baseURL+"list?limit="+c);
               
        InputStream in = u.openStream();
        is = new InputSource();
        is.setCharacterStream(new InputStreamReader(in));
        doc = docBuild.parse(is);
        NodeList idNodes = doc.getElementsByTagName("id");
        NodeList titleNodes = doc.getElementsByTagName("title");
        List<Integer> idList = new LinkedList<Integer>();
        List<String> titleList = new LinkedList<String>();
        for (int i=0; i<idNodes.getLength(); i++) {
            idList.add(Integer.parseInt(((CharacterData) idNodes.item(i).getFirstChild()).getData()));
            titleList.add(((CharacterData) titleNodes.item(i).getFirstChild()).getData());
        }
        String outString = "";
        for (int i=0; i<idList.size(); i++) {
            outString += "<article><id>"+idList.get(i)+"</id><title>"+titleList.get(i)+"</title></article>";
        }
        return "<list>"+outString+"</list>";
        } catch (Throwable t) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            return "ERROR: " + t.getMessage() + "\n" + sw.toString();
        }
    }

    @WebMethod(operationName = "getArticle")
    public String getArticle(@WebParam(name = "id") String id) {
        try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(id));
        Document doc = docBuild.parse(is);
        
        Integer c = null;
        c = Integer.parseInt(((CharacterData) doc.getElementsByTagName("id").item(0).getFirstChild()).getData());
        URL u = new URL(baseURL+c);
               
        InputStream in = u.openStream();
        is = new InputSource();
        is.setCharacterStream(new InputStreamReader(in));
        doc = docBuild.parse(is);
        Map<String,String> set = new HashMap<String,String>();
        NodeList children = doc.getElementsByTagName("article").item(0).getChildNodes();
        for (int i=0; i<children.getLength(); i++) {
            Node child = children.item(i);
            String childName = child.getNodeName();
            String childData = ((CharacterData) (child.getFirstChild())).getData();
            set.put(childName, childData);
        }
        
        return "<article><id>"+set.get("id")+"</id><title>"+set.get("title")+
                "</title><content>"+set.get("content")+"</content><time>"+set.get("date")+"</time><authorID>"+set.get("authorID")+"</authorID></article>";
        } catch (Throwable t) {
            return "<error>"+t+"</error>";
        }
    }

    @WebMethod(operationName = "getAuthor")
    public String getAuthor(@WebParam(name = "id")
    String id) {
        try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(id));
        Document doc = docBuild.parse(is);
        
        Integer c = null;
        c = Integer.parseInt(((CharacterData) doc.getElementsByTagName("id").item(0).getFirstChild()).getData());
        URL u = new URL(baseURL+"author/"+c);
        
        InputStream in = u.openStream();
        is = new InputSource();
        is.setCharacterStream(new InputStreamReader(in));
        doc = docBuild.parse(is);
        
        return "<name>"+doc.getElementsByTagName("name").item(0).getTextContent()+"</name>";
        } catch(Throwable t) {
            return "<error>"+t+"</error>";
        }
    }
    
    @WebMethod(operationName = "browseCategory")
    public String browseCategory(@WebParam(name = "category") String category) {
        try {
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(category));
        Document doc = docBuild.parse(is);
        
        String cat = ((CharacterData) doc.getElementsByTagName("category").item(0).getFirstChild()).getData();
        URL u = new URL(baseURL+"list/"+cat);
        
        InputStream in = u.openStream();
        is = new InputSource();
        is.setCharacterStream(new InputStreamReader(in));
        doc = docBuild.parse(is);
        
        NodeList idNodes = doc.getElementsByTagName("id");
        NodeList titleNodes = doc.getElementsByTagName("title");
        List<Integer> idList = new LinkedList<Integer>();
        List<String> titleList = new LinkedList<String>();
        for (int i=0; i<idNodes.getLength(); i++) {
            idList.add(Integer.parseInt(((CharacterData) idNodes.item(i).getFirstChild()).getData()));
            titleList.add(((CharacterData) titleNodes.item(i).getFirstChild()).getData());
        }
        String outString = "";
        for (int i=0; i<idList.size(); i++) {
            outString += "<article><id>"+idList.get(i)+"</id><title>"+titleList.get(i)+"</title></article>";
        }
        
        return "<list>"+outString+"</list>";
        } catch(Throwable t) {
            return "<error>"+t+"</error>";
        }
    }
    
    @WebMethod(operationName = "listCategories")
    public String listCategories() {
        try {        
        URL u = new URL(baseURL+"keywords");
        
        InputStream in = u.openStream();
        InputSource is = new InputSource();
        is.setCharacterStream(new InputStreamReader(in));
        Document doc = docBuild.parse(is);
        
        NodeList nodes = doc.getElementsByTagName("word");
        List<String> idList = new LinkedList<String>();
        for (int i=0; i<nodes.getLength(); i++) {
            idList.add(((CharacterData) nodes.item(i).getFirstChild()).getData());
        }
        String outString = "";
        for (String c : idList) {
            outString += "<name>"+c+"</name>";
        }
        
        return "<list>"+outString+"</list>";
        } catch(Throwable t) {
            return "<error>"+t+"</error>";
        }
    }

}
